import React, { PureComponent } from 'react';
import { Table, notification  } from 'antd';
import {getDictName} from "../../utils/tool"
import { connect } from 'dva';
import {worker} from "../../utils/worker"
import io from 'socket.io-client'
import {debounce} from "lodash"
const style = {
    input: {
        width: "100%"
    },
    table: {
        marginTop: "20px"
    }
}
class SwitchBridge extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            st: null,
            selectedRowKeys:[],
            qString: "",
            pagination: {
                pageSize: 5,
                pageNum: 1
            },
            msglist:[],
            loading: true,
            total: 0,
            data: []
        }
        this.onConfirm = this.onConfirm.bind(this);
        this.fuzzy = this.fuzzy.bind(this);
        this.select = this.select.bind(this);
        this.paginationChange = this.paginationChange.bind(this)
        this.getData = this.getData.bind(this)
        this.onSelectChange=this.onSelectChange.bind(this)
        this.handleDebounce = debounce(this.getData, 1000, { 'maxWait': 1000 });
        this.initSocket=this.initSocket.bind(this)
    }
    componentDidMount() {
        if (this.props.onLoaded) {
            this.props.onLoaded(this);
        }
        this.getData()

    }
    componentWillUnmount(){
        if(this.st){
            clearTimeout(this.st)
        }
    }
    initSocket() {
        const uuid=new Date().getTime()
        const socket = io(process.env.NODE_ENV=="production"?"192.168.1.102:8000":"192.168.152.31:8000", {
            // path: '/',
            transports: ['websocket', 'polling'],
            query: "uuId=" + uuid,
        })

        socket.on('connect', (res)=>{
            this.props.showCommond(null,true)
        })
        socket.on('calculate', (res)=>{
            this.props.getSocketNews(res)
            let {msglist}=_this.state;
            msglist.push(res)
            this.setState({
                msglist:[...msglist]
            })
        })
        socket.on('msgFinish',  (res)=>{
            this.props.closeBg()
        })
        return uuid
    }
    async getData() {
        let props = this.props;
        let qString = this.state.qString
        let res = await props.bridgeMainAndChild({ projectId: props.project.id, name: qString })
        this.setState({
            loading: false,
            data: await worker.loopTreeNode6(JSON.parse(JSON.stringify(res).replace(/bridges/g,'children'))),

        })
    
    }
    async fuzzy(e) {
        e.persist();
        await this.setState({
            qString: e.target.value
        })
        this.handleDebounce()
    }
    async select(e, item) {
        e.preventDefault()
        e.stopPropagation()
        if (this.props.updateCurrentBridge) {
            this.props.parent.setModalVisible(false)
            await this.props.updateCurrentBridge(item)
            await this.props.queryBridgeDetail({ id: item.id })
            this.props.refresh()
        }

    }
    async paginationChange(pagination) {
        await this.setState({
            pagination: {
                ...this.state.pagination,
                pageNum: pagination.current
            }
        })
        this.getData()
    }
   
    onConfirm(params = {}) {
        let {selectedRowKeys}=this.state;
        this.props.showBg()
        if(selectedRowKeys&&selectedRowKeys.length){
            const uuid=this.initSocket()
            if (params.onSuccess) {
                params.onSuccess(params);
            }
            this.props.caculateDefinitionInstanceProperty({bridgeIds:selectedRowKeys,uuId:uuid},res=>{
    
            },err=>{
                this.props.closeBg()
                if (params.onError) {
                    params.onError("");
                }
            })  
        }else{
            if (params.onError) {
                params.onError("");
            }
            notification.warn({message:"请选择桥梁!"})
        }
        
    }
    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
    };
    render() {
        const {selectedRowKeys}=this.state;
        const {dictlist}=this.props;
        const rowSelection = {
            checkStrictly:true,
            selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps:(record)=>{
                if(record.checkable){
                    return {
                        disabled:false
                    }
                }else{
                    return {
                        disabled:true
                    }
                }
                
            }
        };
        const {
            columns = [
                {
                    title: '中文名',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '桥梁类型',
                    dataIndex: 'bridgeType',
                    key: 'bridgeType',
                    render: (value, record) =>getDictName(dictlist,value)
                    
                },
                {
                    title: '桥宽(m)',
                    dataIndex: 'width',
                    key: 'width'
                    
                },
                {
                    title: '开始桩号',
                    dataIndex: 'startStation',
                    key: 'startStation',
                    
                },
                {
                    title: '中间桩号',
                    dataIndex: 'midStation',
                    key: 'midStation',
                    
                },
                {
                    title: '结束桩号',
                    dataIndex: 'endStation',
                    key: 'endStation',
                    
                }
            ]
        } = this.props;
        return (
            <div>
                {/* <Input style={style.input} onChange={this.fuzzy} placeholder="请输入工程名称" /> */}
                <Table rowSelection={rowSelection} onChange={this.paginationChange} pagination={false} style={style.table} dataSource={this.state.data} columns={columns}
                    loading={this.state.loading}
                    rowKey={record => record.id}>
                </Table>
            </div>
        );
    }
}

export default connect(
    ({ }) => ({}),
    dispatch => ({
        updateCurrentBridge: (bridge) => dispatch({
            type: 'bridge/updateCurrent',
            payload: bridge
        }),
        caculateDefinitionInstanceProperty: (values, onSuccess, onError) => dispatch({
            type: 'bridge/caculateDefinitionInstanceProperty',
            payload: {
                values,onSuccess,onError
            }
        }),
        bridgeMainAndChild: (values) => dispatch({
            type: 'bridge/bridgeMainAndChild',
            payload: values
        }),
        queryBridgeDetail: (values) => dispatch({
            type: 'bridge/queryBridgeDetail',
            payload: values
        }),
    })
)(SwitchBridge);